#include "54func.h"
#include "cmdFunc.h"
#include "log.h"

// 登录用户,cmd_t获取指令及参数
int userLogin(int netfd, cwd_t** ppcwd, const cmd_t *pcmd)
{
    // 获取用户名和密码
    char userName[PATH_MAX] = {0};
    char passWord[PATH_MAX] = {0};
    strcpy(userName,pcmd->argv1);
    strcpy(passWord,pcmd->argv2);
    // 根据用户名获取盐值和密文
    struct spwd *pw;
    // 切换为 root 用户
    if (setuid(0) != 0)
    {
        perror("setuid");
        exit(1);
    }
    // 通过用户名获取用户加密密码信息
    pw = getspnam(userName);
    if (pw == NULL)
    {
        fprintf(stderr, "userLogin: 用户不存在或密码不可访问\n");
        exit(1);
    }
    printf("用户%s的加密密文是: %s\n", userName, pw->sp_pwdp);
    char *encrypted, *salt, *password_crypt;
    for (salt = pw->sp_pwdp, encrypted = pw->sp_pwdp; *encrypted && *encrypted == '$'; encrypted++)
    {
        salt = strchr(encrypted + 1, '$');
        if (salt) {
            encrypted = salt;
        }
    }

    // 对密码进行加密
    password_crypt = crypt(passWord, pw->sp_pwdp);
    ERROR_CHECK(password_crypt,NULL,"crypt failed");

    // 比较新生成的密文和本地密文
    if (strcmp(password_crypt, pw->sp_pwdp) == 0)
    {
        // 登陆成功
        successSend(netfd);
        *ppcwd = (cwd_t *)calloc(1,sizeof(cmd_t));
        cwdInit(userName,ppcwd);
        return 0; // 验证成功
    }
    else
    {
        printf("Password verification failed.\n");
        errorSend(netfd,NULL);
        errorSend(netfd,"密码验证失败!");
        return -1; // 验证失败
    }

    return 0;
}
// 创建用户,cmd_t获取指令及参数
int userAdd(int netfd, const cmd_t *pcmd)
{
    printf("this is userAdd\n");
    return 0;
}
// 退出登录
int userLogout(int netfd, cwd_t** ppcwd, const cmd_t* pcmd)
{
    printf("this is userLogout\n");
    // 报错
    if(*ppcwd == NULL)
    {
        send(netfd,"e",1,MSG_NOSIGNAL);
        train_t train;
        train.length = sizeof("用户未登录!");
        memcpy(train.data,"用户未登录!",train.length);
        send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
        return -1;
    }
    // 销毁栈
    free(*ppcwd);
    *ppcwd = NULL;
    send(netfd,"o",1,MSG_NOSIGNAL);
    return 0;
}

